﻿using System;

namespace BoldBrick.Core.Logging
{
    /// <summary>
    /// This class provides logging
    /// </summary>
	public static class Logger
    {
        private static readonly Type loggerType;

        static Logger()
        {
            EnsureLoggerInitialized();

            // prepare logger type for creating logger instances
            loggerType = Type.GetType(Properties.LoggerSettings.Default.LoggerTypeName, true);
        }

		/// <summary>
		/// Ensured that a logger is initialized and ready to use
		/// </summary>
        private static void EnsureLoggerInitialized()
        {
            string loggerInitTypeName = Properties.LoggerSettings.Default.LoggerInitTypeName;
            if (string.IsNullOrEmpty(loggerInitTypeName))
                return;

            // init logger
            Type loggerInitType = Type.GetType(loggerInitTypeName, true);
            // get logger class
            ILoggerInit loggerInit = Activator.CreateInstance(loggerInitType, null) as ILoggerInit;

            // which context to run for init?
            string loggerInitCtxTypeName = Properties.LoggerSettings.Default.LoggerInitContextTypeName;
            if (string.IsNullOrEmpty(loggerInitCtxTypeName))
            {
                // direct init
                loggerInit.Init();
            }
            else
            {
                // get context to run logger init
                Type loggerInitCtxType = Type.GetType(loggerInitCtxTypeName, true);

                // get context wrapper instance
                ILoggerInitContext loggerInitCtx = Activator.CreateInstance(loggerInitCtxType, null) as ILoggerInitContext;
                loggerInitCtx.InitLoggerInContext(loggerInit);
            }
        }
          
		/// <summary>
		/// Created logger for specified type
		/// </summary>
		/// <typeparam name="Class">Type of class from which will logged</typeparam>
		/// <returns>Returns logger for specified type</returns>
        public static ILogger GetLogger<Class>()
            where Class: class
        {
            // run constructor with one parameter as logging class
            return Activator.CreateInstance(loggerType, new object[] {typeof(Class)}) as ILogger;
        }

		/// <summary>
		/// Created logger for specified type
		/// </summary>
		/// <param name="_class">Type of class from which will logged</param>
		/// <returns>Returns logger for specified type</returns>
        public static ILogger GetLogger(Type _class)
        {
            // run constructor with one parameter as logging class
            return Activator.CreateInstance(loggerType, new object[] { _class }) as ILogger;
        }
    }
}
